package com.sinoatma.physignsmonitor.fragment

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.common.frame.base.BaseViewModel
import com.common.frame.base.isDebug
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.ValueFormatter
import com.google.gson.Gson
import com.sinoatma.physignsmonitor.MyApp
import com.sinoatma.physignsmonitor.bean.BpDataBean
import com.sinoatma.physignsmonitor.bean.ExcelColumnHead
import com.sinoatma.physignsmonitor.bean.MonitorRecordEntity
import com.sinoatma.physignsmonitor.bean.MonitorRecordsBean
import com.sinoatma.physignsmonitor.constant.BloodTransfusionModeFlag
import com.sinoatma.physignsmonitor.constant.BloodTypeModeFlag
import com.sinoatma.physignsmonitor.constant.devicesNumber
import com.sinoatma.physignsmonitor.http.NetManager
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.text.SimpleDateFormat
import java.util.*

/**
 * @ProjectName : PhySignsMonitor
 * @Author :
 * @Time : 2025/1/10 11:48
 * @Description : 文件描述
 */
class BloodTransViewModel:BaseViewModel() {
    val sdfFile = SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss")

    val sdfDate = SimpleDateFormat("yyyy年MM月dd日")
    val sdfDateTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val sdfEarlyWarning = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
    val sdfWarning = SimpleDateFormat("HH:mm:ss")
    var scanType=0
    var random = Random() // 随机数生成器
    var oxygenData: ArrayList<Entry> = ArrayList() // 血氧数据集合
    var pulseData: ArrayList<Entry> = ArrayList() //  心率数据集合
    var temperatureData: ArrayList<Entry> = ArrayList() //  心率数据集合
    var timeStamps1: ArrayList<String> = ArrayList()
    var timeStamps2: ArrayList<String> = ArrayList()
    var bpList1 = mutableListOf<BpDataBean>()

    var bpData1=""

    var monitorCode1:String=""
    var monitorName1:String=""
    var monitorSex1:String=""
    var monitorAge1:String=""

    var filePath:String=""

    var headList : ArrayList<ExcelColumnHead> =  ArrayList()

    var excelListData: ArrayList<MonitorRecordsBean> = ArrayList()

    var excelListDataTemp:ArrayList<MonitorRecordsBean> = ArrayList()

    var o2ringConnectStatus1=0

    var bPConnectStatus1=false

    var tempConnectStatus1=false

    var alertStatusRecordSpo1=""
    var alertStatusRecordPr1 =""
    var alertStatusRecordBp1 =""
    var alertStatusRecordTemp1 =""

    var alertStatusValueSpo1=""
    var alertStatusValuePr1 =""
    var alertStatusValueBp1 =""
    var alertStatusValueTemp1 =""

    var temperature=""

    var numberEarlyWarning1=0

    var excelId=""

    var dataMsg : MutableLiveData<String> = MutableLiveData()


    /**
     * 采血异常接口
     * warn     预警类型（10：血氧饱和度；20：脉搏；30：血压；40：体温）
     * status   预警状态（10：开始；0：结束）
     * reason  预警原因
     *
     */
    fun exception(warn:String,status:String,reason:String,value:String){
        val jsonMap = HashMap<String, String>()
        jsonMap["donorCode"]=monitorCode1
        jsonMap["warn"]=warn
        jsonMap["status"]=status
        jsonMap["reason"]=reason
        jsonMap["value"]=value
        jsonMap["time"]=sdfDateTime.format(Date())
        val gson = Gson()
        val toJson = gson.toJson(jsonMap)
        launchRequest({NetManager.exception(RequestBody.create("application/json;charset=UTF-8".toMediaTypeOrNull(), toJson))},{
        },{
        },false)
    }



    /**
     * 文件上传接口
     */
    fun uploadFile(file: File){
        Log.e("zsy","${file.length()}  +${file.path}")
        val donorCodeBody: RequestBody = excelId.toRequestBody("text/plain".toMediaTypeOrNull())
        val requestFile: RequestBody = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
        var filePart: MultipartBody.Part= MultipartBody.Part.createFormData("file", file.name, requestFile)
        launchRequest({ NetManager.uploadFile(donorCodeBody,filePart)},{
            Log.e("zsy","上传成功")
            dataMsg.value="1"
        },{
            Log.e("zsy","上传失败=${it.code} ${it.msg}  ${it.message}")
            dataMsg.value="上传失败=${it.code} ${it.msg}  ${it.message}"
        },showLoading = false)
    }


    /**
     * 信息上传接口
     */
    fun uploadInfo(){
        val jsonMap = HashMap<String, String>()
        jsonMap["donorCode"]=monitorCode1
        jsonMap["name"]=monitorName1
        jsonMap["sex"]=if (monitorSex1=="男") "10" else "20"
        jsonMap["age"]=monitorAge1
        if (BloodTransfusionModeFlag==1){
           if (BloodTypeModeFlag==1)  "10" else "20"
        }else{
            jsonMap["type"]=if (BloodTransfusionModeFlag==1) "10" else "30"
        }

        jsonMap["status"]="10"
        jsonMap["deviceNumber"]= devicesNumber
        val gson = Gson()
        val toJson = gson.toJson(jsonMap)
        launchRequest({NetManager.personalInfo(RequestBody.create("application/json;charset=UTF-8".toMediaTypeOrNull(), toJson))},{
            Log.e("zsy","id=${it.id}")
            excelId=it.id
        },{

        },showLoading = false)
    }

    fun  initHeadExcel(){
        headList.add(ExcelColumnHead("献血码",5000))
        headList.add(ExcelColumnHead("姓名",3000))
        headList.add(ExcelColumnHead("性别",2000))
        headList.add(ExcelColumnHead("年龄",2000))
        headList.add(ExcelColumnHead("血氧饱和度(%)",4000))
        headList.add(ExcelColumnHead("血压(mmHg)",4000))
        headList.add(ExcelColumnHead("脉搏(分/次)",3000))
        headList.add(ExcelColumnHead("体温(℃)",3000))
        headList.add(ExcelColumnHead("监护时间",5500))
        headList.add(ExcelColumnHead("预警时间",6500))
        headList.add(ExcelColumnHead("预警原因",8000))
        headList.add(ExcelColumnHead("数据采集设备编码",5000))
    }

    // 自定义电压刻度格式
    inner class OxygenFormatter : ValueFormatter() {
        override fun getFormattedValue(value: Float): String {
            return value.toInt().toString()
        }
    }

    // 自定义电流刻度格式
    inner class HeartFormatter : ValueFormatter() {
        override fun getFormattedValue(value: Float): String {
            return value.toInt().toString()  // 显示单位为"A"
        }
    }

    // 自定义电流刻度格式
    inner class TemperatureFormatter : ValueFormatter() {
        override fun getFormattedValue(value: Float): String {
            return value.toInt().toString()  // 显示单位为"A"
        }
    }
    // 自定义电流刻度格式
    inner class TemperatureRightFormatter : ValueFormatter() {
        override fun getFormattedValue(value: Float): String {
            return ""  // 显示单位为"A"
        }
    }

    fun  initExcelFolder(name:String,code:String){
        val dir = File(MyApp.context.getExternalFilesDir(null), "sinoatma/Excel")
        if (!dir.exists()) {
            dir.mkdirs()
        }
        filePath="${dir}/${name}-${code}-${sdfFile.format(Date())}.xlsx"
    }


    // 插入数据
    fun insertRecord(record: MonitorRecordEntity) {
        viewModelScope.launch {
            MyApp.monitorRecordDao.insert(record)
        }
    }

    fun hexStringToFloat(hexString: String): Float {
        // 确保十六进制字符串长度为8（对应4个字节）
        require(hexString.length == 8) { "输入的十六进制字符串长度必须为8" }
        val byteArray = ByteArray(4)
        // 将十六进制字符串每两位解析为一个字节，按小端序放入字节数组
        for (i in 0 until 4) {
            byteArray[i] = hexString.substring(i * 2, (i + 1) * 2).toInt(16).toByte()
        }
        val buffer = ByteBuffer.wrap(byteArray).order(ByteOrder.LITTLE_ENDIAN)
        return buffer.float
    }

}